package cn.ml.duoXianCheng.qiangPiao;

public class QiangPiao2 implements Runnable{
    private int count=10;  //记录剩余票数
    private int num = 0;   //记录买到第几张票
    public void run() {
        try {
            Thread.sleep(0);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        while (true) {
            //同步代码块
            synchronized (this) {
                // 没有余票时，跳出循环
                if (count <= 0) {
                    break;
                }
                // 第一步：修改数据
                num++;
                count--;
                try {
                    Thread.sleep(50); // 模拟网络延时
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                // 第二步：显示信息
                System.out.println(Thread.currentThread().getName() + "抢到第"
                        + num + "张票，剩余" + count + "张票！");
            }

            //消化过程不能再锁里
//            int rd = (int) (Math.random() * 0);   //随机生成200的随机数
            try {
                Thread.sleep(2);   //吃的过程消化rd毫秒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        QiangPiao2 site = new QiangPiao2();
        Thread person1= new Thread(site,"桃跑跑");
        Thread person2= new Thread(site,"抢票代理");
        Thread person3= new Thread(site,"黄牛党");
        System.out.println("********开始抢票********");
        person1.start();
        person2.start();
        person3.start();
    }

}
